package com.wisdomelon.config;

import com.wisdomelon.config.bean.CorsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

/**
 * @author wisdomelon
 * @date 2020/2/27 0027
 * @project services
 * @jdk 1.8
 * 配置跨域过滤器
 */
@Configuration
public class AccessCorsConfig {

    @Autowired
    private CorsConfig corsConfig;

    @Bean
    public CorsFilter corsFilter() {

        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedOrigins(corsConfig.getAllowOrigins());
        config.setAllowedHeaders(Arrays.asList("access_token", "Origin", "X-Requested-With", "Content-Type", "Accept"));
        config.setAllowedMethods(Arrays.asList("GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "OPTIONS", "PATCH"));
        config.setMaxAge(300L);
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
}
